package com.young.ysepay.service.impl;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.young.ysepay.domain.YsRoutingReceiptDO;
import com.young.ysepay.mq.YsReturnMQConfig;
import com.young.ysepay.service.YsAsyncService;
import com.young.ysepay.service.YsNotifyRegistryService;
import com.young.ysepay.service.YsRoutingReceiptService;
import com.young.ysepay.service.YsVerifyJsonSignService;
import com.young.ysepay.utils.JSONUtils;
import com.young.ysepay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.function.ObjDoubleConsumer;

/**
 * @Author zhaopengjun
 * @Description //银盛分账异步回执
 * @Date 17:26 2019/6/10
 * @Param 
 * @return 
 **/
@Service
public class YsAsyncServiceImpl implements YsAsyncService {
    @Autowired
    YsVerifyJsonSignService ysVerifyJsonSignService;
    @Autowired
    YsNotifyRegistryService ysNotifyRegistryService;
    @Autowired(required = false)
    private Producer producer;
    @Autowired
    private YsRoutingReceiptService ysRoutingReceiptService;
    private static Logger log = LoggerFactory.getLogger(YsAsyncServiceImpl.class);
    @Override
    public void ysAsynchronousReturn(Map<String,String> paramMap, HttpServletResponse response) {
        PrintWriter out = null;
        log.error("YsAsyncServiceImpl.ysAsynchronousReturn()------银盛分账异步回执json为:"+JSONUtils.toJSon(paramMap));
        if(null == paramMap || paramMap.size()<0 ){
             ApiResult.failure("银盛分账异步回执结果为空");
        }
        try {
            this.saveAsyncRouting(paramMap);
            Message message = null;
            boolean verifyResult = ysVerifyJsonSignService.verifySign(paramMap);
            out = response.getWriter();
            // 状态
            if (verifyResult) {// 验证成功
                message = new Message(YsReturnMQConfig.SETTLETOPIC, YsReturnMQConfig.YSSPLITRECEIPT_TAG, JSONUtils.objectToJson(paramMap).getBytes());
                producer.send(message);
                log.info("异步分账回执通知成功信息"+new String(message.getBody()));
                out.println("success"); }
                else {// 验证失败
                log.info("异步通知验证签名失败"+new String(message.getBody()));
                out.println("fail");
            }
        } catch (Exception e) {
            log.error("银盛异步分账回执接口",e.getMessage());
            e.printStackTrace();
        }finally {
            if (out != null){
                out.close();
            }
        }
    }

    private void saveAsyncRouting(Map<String,String> paramMap) {
        log.info("银盛分账异步保存参数明细"+JSONUtils.objectToJson(paramMap));
        YsRoutingReceiptDO ysRoutingReceiptDO = new YsRoutingReceiptDO();
        try {
            //获取分账异步通知参数保存回执表
            Object temp = "";
            temp = paramMap.get("total_amount");
            String total_amount = temp != null? temp.toString():null;
            temp = paramMap.get("notify_time");
            String notify_time = temp != null? temp.toString():null;
            temp = paramMap.get("detailResults");
            String detailResults = temp != null? temp.toString():null;
            temp = paramMap.get("division_status_code");
            String division_status_code = temp != null? temp.toString():null;
            temp = paramMap.get("sign_type");
            String sign_type = temp != null? temp.toString():null;
            temp = paramMap.get("fee_payer");
            String fee_payer = temp != null? temp.toString():null;
            temp = paramMap.get("notify_type");
            String notify_type = temp != null? temp.toString():null;
            temp = paramMap.get("out_trade_no");
            String out_trade_no = temp != null? temp.toString():null;
            temp = paramMap.get("fee");
            String fee = temp != null? temp.toString():null;
            temp = paramMap.get("src_usercode");
            String src_usercode = temp != null? temp.toString():null;
            temp = paramMap.get("division_mode");
            String division_mode = temp != null? temp.toString():null;
            temp = paramMap.get("note");
            String note = temp != null? temp.toString():null;
            temp = paramMap.get("division_status");
            String division_status = temp != null? temp.toString():null;
            ysRoutingReceiptDO.setOutTradeNo(out_trade_no);
            ysRoutingReceiptDO.setDivisionStatusCode(division_status_code);
            ysRoutingReceiptDO.setDivisionStatus(division_status);
            ysRoutingReceiptDO.setResponseType("2");
            ysRoutingReceiptDO.setIsDelete("1");
            ysRoutingReceiptDO.setGmtModified(new Date());
            ysRoutingReceiptDO.setGmtCreate(new Date());
            ysRoutingReceiptDO.setDetailResults(detailResults);
            ysRoutingReceiptDO.setDivisionMode(division_mode);
            ysRoutingReceiptDO.setFee(new BigDecimal(fee));
            ysRoutingReceiptDO.setNote(note);
            ysRoutingReceiptDO.setFeePayer(fee_payer);
            ysRoutingReceiptDO.setNotifyTime(notify_time);
            ysRoutingReceiptDO.setNotifyType(notify_type);
            ysRoutingReceiptDO.setSignType(sign_type);
            ysRoutingReceiptDO.setSrcUsercode(src_usercode);
            ysRoutingReceiptDO.setTotalAmount(new BigDecimal(total_amount));
            ysRoutingReceiptService.save(ysRoutingReceiptDO);
        }catch (Exception e){
            log.error("银盛分账异步回执日志记录保存失败"+ysRoutingReceiptDO.toString());
        }

    }
}
